package com.dw.etl.core.service;

import com.dw.etl.core.api.BaseDbService;
import com.dw.etl.core.bean.model.BaseDb;
import com.dw.etl.core.db.DynamicDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liujunlei on 2021/5/27.
 */
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
    @Autowired
    BaseDbService baseDbService;

    @Autowired
    DynamicDataSource dynamicDataSource;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        //装配所有数据源
        List<BaseDb> baseDbList = baseDbService.findByModel(new BaseDb());
        Map<Object,Object> dataSourceMap = DynamicDataSource.dataSourceMap;
        HikariDataSource dataSource;
        for(BaseDb baseDb:baseDbList) {
            dataSource = new HikariDataSource();
            dataSource.setJdbcUrl(baseDb.getUrl());
            dataSource.setUsername(baseDb.getUsename());
            dataSource.setPassword(baseDb.getPsword());
            dataSource.setDriverClassName(baseDb.getDriver());
            dataSourceMap.put(baseDb.getIdDb()+"",dataSource);
        }
        dynamicDataSource.setTargetDataSources(DynamicDataSource.dataSourceMap);
    }
}
